/* cl.ext.ext.selectedmove 0.1*/
(
    function (factory) {
        if (typeof define === 'function' && define.amd) {
            define(['jquery'], factory);
        } else if (typeof module === 'object' && module.exports) {
            module.exports = function( root, jQuery ) {
                if ( jQuery === undefined ) {
                    if ( typeof window !== 'undefined' ) {
                        jQuery = require('jquery');
                    }
                    else {
                        jQuery = require('jquery')(root);
                    }
                }
                factory(jQuery);
            };
        } else {
            factory(jQuery);
        }
    }(
        function ($){
            var defaultsConfig={
                weekName:[{id:1,name:"周一"},{id:2,name:"周二"},{id:3,name:"周三"},{id:4,name:"周四"},{id:5,name:"周五"},{id:6,name:"周六"},{id:7,name:"周日"}],
                week:[1,2,3,4,5,6,7],
                hour:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],
                tableColumn:["0","1","2","3","4","5","6","7","","8","9","10","11","","12","13","14","","15","16","17","","18","19","","20","21","22","23"],
                quickName:[
                    {id:"weekday",name:"工作日"},
                    {id:"weekend",name:"周末"},
                    {id:"dawn",name:"凌晨"},
                    {id:"morning",name:"上午"},
                    {id:"noon",name:"中午"},
                    {id:"afternoon",name:"下午"},
                    {id:"evening",name:"傍晚"},
                    {id:"night",name:"晚上"}
                ],
                quick:{
                    weekday:{week:[1,2,3,4,5],hour:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]},
                    weekend:{week:[6,7],hour:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]},
                    dawn:{week:[1,2,3,4,5,6,7],hour:[0,1,2,3,4,5,6,7]},
                    morning:{week:[1,2,3,4,5,6,7],hour:[8,9,10,11]},
                    noon:{week:[1,2,3,4,5,6,7],hour:[12,13,14]},
                    afternoon:{week:[1,2,3,4,5,6,7],hour:[15,16,17]},
                    evening:{week:[1,2,3,4,5,6,7],hour:[18,19]},
                    night:{week:[1,2,3,4,5,6,7],hour:[20,21,22,23]}
                }
            };
            var defaults={
                initvalue:"",
                infoConfig:defaultsConfig,
                initCallback:null
                //changeCallback:null //待需求实现
            };
            var $modalCommon={
                getDefaults :function () {
                    return defaults
                },
                getOptions : function (elementData,options) {
                    options=$.ExtCommon.isCheckEmpty(options)?{}:options;
                    var optionBase =$.ExtCommon.initMergeJson(elementData,options);
                    optionBase =$.ExtCommon.initMergeJson(this.getDefaults(),optionBase);
                    return optionBase
                }
            };
            var modalOperateElement=function(element,options){
                var self=this;
                self.optionModal=options;
                self.elementModal = element;
            };
            modalOperateElement.prototype = {
                init:function(){
                    this.bindEvent();
                },
                bindEvent:function(){
                    var self=this;
                    //快捷
                    self.elementModal.quickclassify.children("a").hover(function(){
                        var thisData=$(this).data();
                        self.hoverIn(thisData.week,thisData.hour)
                    }, function(){
                        self.hoverOut()
                    });
                    self.elementModal.quickclassify.children("a").on("click",function(){
                        var thisData=$(this).data();
                        var jsonWeekHour=self.getToggleJson(thisData.week,thisData.hour);
                        self.toggleSelected(jsonWeekHour)
                    });
                    //全选/清空
                    self.elementModal.quickoperate.children("a").on("click",function(){
                        var type=$(this).data("type");
                        switch (type){
                            case "all":
                                self.allSelected();
                                break;
                            case "clear":
                                self.clearSelected();
                                break;
                        }
                    });
                    //table- hour-title
                    self.elementModal.tableHead.find(".hour-title").hover(function(){
                        var thisData=$(this).data();
                        self.hoverIn(self.optionModal.infoConfig.week,[parseInt(thisData.hour)])
                    }, function(){
                        self.hoverOut()
                    });
                    self.elementModal.tableHead.find(".hour-title").on("click",function(){
                        var thisData=$(this).data();
                        var jsonWeekHour=self.getToggleJson(self.optionModal.infoConfig.week,[thisData.hour]);
                        self.toggleSelected(jsonWeekHour)
                    });
                    //table- week-title
                    self.elementModal.tableBody.find(".week-title").hover(function(){
                        var thisData=$(this).data();
                        self.hoverIn([parseInt(thisData.week)],self.optionModal.infoConfig.hour)
                    }, function(){
                        self.hoverOut()
                    });
                    self.elementModal.tableBody.find(".week-title").on("click",function(){
                        var thisData=$(this).data();
                        var jsonWeekHour=self.getToggleJson([thisData.week],self.optionModal.infoConfig.hour);
                        self.toggleSelected(jsonWeekHour)
                    });
                    //table- week-hour
                    self.elementModal.tableBody.find(".week-hour").hover(function(){
                        var thisData=$(this).data();
                        self.hoverIn([parseInt(thisData.week)],self.optionModal.infoConfig.hour);
                        self.hoverIn(self.optionModal.infoConfig.week,[parseInt(thisData.hour)]);
                    }, function(){
                        self.hoverOut()
                    });
                    self.elementModal.tableBody.find(".week-hour").on("click",function(){
                        var thisData=$(this).data();
                        var jsonWeekHour=self.getToggleJson([thisData.week],[thisData.hour]);
                        self.toggleSelected(jsonWeekHour)
                    });
                },
                getToggleJson:function(week,hour){
                    var json={};
                    $.each(week,function(i,w){
                        json[w.toString()]=hour;
                    });
                    return json;
                },
                hoverIn:function(week,hour){
                    var self=this;
                    $.each(week,function(i,w){
                        var elementTr=self.elementModal.tableBody.children("tr").eq(w-1);
                        $.each(hour,function(i,h){
                            elementTr.children("td").not(".hour-interval").eq(h+1).addClass("week-hour-hover");
                        });
                    });
                },
                hoverOut:function(){
                    this.elementModal.table.find(".week-hour-hover").removeClass("week-hour-hover")
                },
                toggleSelected:function(jsonWeekHour){
                    if(!$.ExtCommon.isCheckEmpty(jsonWeekHour)) {
                        var self = this;
                        var arrSelected = [];
                        var arrElementTd = [];
                        var week=[];
                        for (var w in jsonWeekHour) {
                            week.push(w);
                            var elementTr = self.elementModal.tableBody.children("tr").eq(parseInt(w) - 1);
                            var elementTd = $.map(jsonWeekHour[w], function (h) {return elementTr.children("td:not(.week-title)").not(".hour-interval").eq(h)});
                            var elementSelected = $.map(elementTd, function (s) {if (s.hasClass("week-hour-selected")) {return s}});
                            arrSelected.push(elementTd.length != elementSelected.length);
                            arrElementTd = arrElementTd.concat(elementTd);
                        }
                        var isSelected = $.map(arrSelected, function (s) {if (!s) {return s}}).length != week.length;
                        $.each(arrElementTd, function (i, td) {isSelected ? td.addClass("week-hour-selected") : td.removeClass("week-hour-selected")});
                    }
                },
                allSelected:function(){
                    this.elementModal.tableBody.find("td:not(.week-title)").not(".hour-interval").addClass("week-hour-selected")
                },
                clearSelected:function(){
                    this.elementModal.tableBody.find("td").removeClass("week-hour-selected")
                },
                createInitWeekHourValue: function () {
                    var infoWeek = {};
                    for (var i = 1; i <= 7; i++) {
                        var infoHour = [];
                        for (var j = 0; j < 24; j++) {
                            infoHour.push(0);
                        }
                        infoWeek[i.toString()] = infoHour;
                    }
                    return infoWeek;
                },
                setSelectedValue:function(jsonWeekHour){
                    var self=this;
                    self.clearSelected();
                    self.toggleSelected(jsonWeekHour);
                },
                getSelectedValue:function(){
                    var self=this;
                    var elementSelected=self.elementModal.tableBody.find(".week-hour.week-hour-selected");
                    var infoWeekHour=self.createInitWeekHourValue();
                    if(elementSelected.length>0) {
                        $.each(elementSelected, function (i, item) {
                            var thisData = $(this).data();
                            infoWeekHour[thisData.week.toString()][parseInt(thisData.hour)] = 1
                        });
                    }
                    return infoWeekHour;
                },
                getSelectedHtml:function(){
                    var self=this;
                    var infoWeekHour=self.getSelectedValue();
                    return $.ExtCommon.convertWeekHourValue(infoWeekHour);
                },
                convertValueByJson: function (arr) {
                    var infoWeekHour = {};
                    $.each(arr, function (i, info) {
                        infoWeekHour[(i + 1).toString()] = info;
                    });
                    return infoWeekHour;
                }
            };
            var WeekHourExtModal = function(element, options) {
                var self=this;
                self.element = $(element);
                self.optionBase=$modalCommon.getOptions(self.element.data(),options);
                //基础html
                var $templateHtml = $('<div class="week-hour-quick">'+
                        '<div class="row">'+
                            '<div class="col-xs-8"><div class="time-quick-classify"></div></div>'+
                            '<div class="col-xs-4"><div class="pull-right time-quick-operate"><a href="javascript:" data-type="all">全选</a><a href="javascript:" data-type="clear">清空</a></div></div>'+
                        '</div>'+
                    '</div>'+
                    '<div class="week-hour-picker"><table class="week-hour-single"><thead></thead><tbody></tbody></table></div>'+
                    '<div class="week-hour-tips"><span class="week-hour week-hour-normal week-hour-selected"><i></i></span><span class="tips-title">已定向</span> &nbsp;&nbsp;<span class="week-hour week-hour-normal"><i></i></span><span class="tips-title">未定向</span></div>');
                self.elementContainer={
                    table:$templateHtml.find(".week-hour-single"),
                    tableHead:null,
                    tableBody:null,
                    quickclassify:$templateHtml.find(".time-quick-classify"),
                    quickoperate:$templateHtml.find(".time-quick-operate")
                };
                self.element.addClass("panel-week-hour").append($templateHtml);
                var infoConfig=self.optionBase.infoConfig;
                //快捷
                var $HtmlQuick=$.map(infoConfig.quickName,function(info){
                    var configQuick=infoConfig.quick[info.id];
                    return $('<a href="javascript:">'+info.name+'</a>').data({type:info.id,"week":configQuick.week,hour:configQuick.hour})
                });
                self.elementContainer.quickclassify.append($HtmlQuick);
                //thead
                var elementTHead=$("<tr><th><span></span></th></tr>");
                var $THead= $.map(infoConfig.tableColumn,function(info){return info.length==0?$('<th class="hour-interval"></th>'):$('<th class="hour-title"><span>'+info+'</span></td>').data({hour:info});});
                elementTHead.append($THead);
                self.elementContainer.table.children("thead").append(elementTHead);
                self.elementContainer.tableHead=self.elementContainer.table.children("thead");
                //tbody
                var $TBody=$.map(infoConfig.weekName,function(w){
                    var $tempTd= $.map(infoConfig.tableColumn,function(h){return h.length==0?$('<td class="hour-interval"></td>'):$('<td class="week-hour week-hour-normal"><i></i></td>').data({"week":w.id,hour:h});});
                    var tempTr=$( '<tr><td class="week-title"><span>'+ w.name+'</span></td></tr>');
                    tempTr.append($tempTd);
                    tempTr.children(".week-title").data({week: w.id});
                    return tempTr
                });
                self.elementContainer.table.children("tbody").append($TBody);
                self.elementContainer.tableBody=self.elementContainer.table.children("tbody");
                self.elementOperate=new modalOperateElement(self.elementContainer,self.optionBase);
                self.elementOperate.init();
                if (!$.ExtCommon.isCheckEmpty(self.optionBase.initvalue)) {
                    self.setSelected(self.optionBase.initvalue);
                }
                if (self.optionBase.initCallback) {self.optionBase.initCallback()}
            };
            WeekHourExtModal.prototype = {
                getSelected:function(){
                    return this.elementOperate.getSelectedValue();
                },
                getSelectedHtml:function(){
                    return this.elementOperate.getSelectedHtml();
                },
                setSelected:function(value){
                    this.elementOperate.setSelectedValue(value);
                },
                clearSelected:function(){
                    this.elementOperate.clearSelected();
                }
            };
            $.fn.ExtWeekHour = function(options) {
                var dataFun;
                this.each(function() {
                    var el = $(this);
                    var tempData=el.data('ExtWeekHour');
                    if (tempData) {
                        if (typeof  options == "string") {
                            if (tempData[options]) {
                                dataFun =tempData[options]()
                            } else {
                                dataFun = tempData
                            }
                        } else {
                            dataFun = tempData
                        }
                    } else {
                        dataFun = new WeekHourExtModal(el, options);
                        el.data('ExtWeekHour', dataFun);
                    }
                });
                return dataFun;
            };
            return WeekHourExtModal;
        })
);
